package com.five.admin.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.five.admin.dto.UserQueryDto;
import com.five.admin.dto.UserUpdateDto;
import com.five.admin.mapper.UserMapper;
import com.five.admin.server.UserService;
import com.five.core.exception.CustomerException;
import com.five.core.result.ResultEnum;
import com.five.core.utils.Md5Utils;
import com.five.pojo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Page<User>  userQuery(UserQueryDto userQueryDto) {
        Page<User> page = new Page<>(userQueryDto.getPage(),userQueryDto.getLimit());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (userQueryDto.getUsername() != null && !userQueryDto.getUsername().trim().isEmpty()) {
            queryWrapper.like("username", userQueryDto.getUsername().trim());
        }

        // 手机号模糊查询
        if (userQueryDto.getPhone() != null && !userQueryDto.getPhone().trim().isEmpty()) {
            queryWrapper.like("phone", userQueryDto.getPhone().trim());
        }

        // 邮箱模糊查询
        if (userQueryDto.getEmail() != null && !userQueryDto.getEmail().trim().isEmpty()) {
            queryWrapper.like("email", userQueryDto.getEmail().trim());
        }

        // 注册时间范围查询（假设数据库字段为created，格式为datetime）
        if (userQueryDto.getStartTime() != null && !userQueryDto.getStartTime().trim().isEmpty()) {
            // 开始时间：>=  startTime 00:00:00
            queryWrapper.ge("created", userQueryDto.getStartTime().trim() + " 00:00:00");
        }
        if (userQueryDto.getEndTime() != null && !userQueryDto.getEndTime().trim().isEmpty()) {
            // 结束时间：<=  endTime 23:59:59
            queryWrapper.le("created", userQueryDto.getEndTime().trim() + " 23:59:59");
        }

        // 按注册时间倒序（最新的用户排在前面）
        queryWrapper.orderByDesc("created");

        return getBaseMapper().selectPage(page, queryWrapper);
    }

    @Override
    public boolean resetPassword(UserUpdateDto userUpdateDto) {
        if (userUpdateDto ==null){
            throw new CustomerException(ResultEnum.VALIDATE_FAIL);
        }
        User user = getBaseMapper().selectById(userUpdateDto.getId());
        if (user==null){
            throw new CustomerException(ResultEnum.USER_NOT_EXIST);
        }
        if (userUpdateDto.getNewPassword().isEmpty()){
            throw new CustomerException("用户密码不能为空");
        }
        String salt = Md5Utils.createSalt();
        String newPwd = Md5Utils.md5Password(userUpdateDto.getNewPassword(), salt);
        user.setPassword(newPwd);
        user.setSalt(salt);
        return getBaseMapper().updateById(user)>0;
    }
}
